package com.qf.sy2103.fmmall.service.impl;

import com.qf.sy2103.common.vo.ResStatus;
import com.qf.sy2103.common.vo.ResultVO;
import com.qf.sy2103.fmmall.beans.entity.Orders;
import com.qf.sy2103.fmmall.service.OrderService;
import com.qf.sy2103.fmmall.wxpay.WxpayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {


    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized ResultVO addOrder(String cids, Orders order) {

        // 1. 检查库存 ， 所有购物车中的商品都要有库存，才可以下单成功

        // 2. 写订单表信息
        // 2.1 写订单主表信息

        // 2.2 写订单明细表信息

        // 3. 购物车中对应的商品的记录需要删除掉

        // 4. 减少库存

        // 5. 调用外部接口获取数据 ，调用微信支付平台获取支付url
        final String orderid = UUID.randomUUID().toString().replaceAll("-","");
        String payUrl = null;
        try {
            payUrl = WxpayUtils.getPayUrl(orderid);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 6. 准备返回数据
        final HashMap<String, String> map = new HashMap<>();
        if (payUrl != null) {
            map.put("payUrl",payUrl);
        }
        map.put("orderId",orderid);
        map.put("totalPrice","1");

        final ResultVO resultVO = new ResultVO();
        resultVO.setCode(ResStatus.OK);
        resultVO.setData(map);
        resultVO.setMsg("success");

        return resultVO;
    }

    @Override
    public ResultVO queryOrderStatus(String orderId) {
        ResultVO vo = new ResultVO();

        try {
            String s = WxpayUtils.queryOrder(orderId);
            if (s!=null && s.equals("SUCCESS")){
                vo.setCode(ResStatus.OK);
                vo.setMsg("success");
                vo.setData(ResStatus.WX_PAY_OK);  // 成功的标识
            }else{
                vo.setCode(ResStatus.NO);
                vo.setMsg("该订单尚未支付成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return vo;
    }
}
